<template>
  <div class="detail-page">
    <el-card shadow="never" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span>详情</span>
        <el-button 
          type="text" 
          style="float: right;"
          :class="{ 'is-collected': isCollected }"
          @click="handleCollect">
          <i :class="isCollected ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
          {{ isCollected ? '已收藏' : '收藏' }}
        </el-button>
        <el-button type="text" style="float: right; margin-right: 10px; color: #409eff;">分享</el-button>
        <el-button type="text" 
                   style="float: right; margin-right: 10px; color: #409eff;"
                   @click="showPhoneDialog">电话联系TA</el-button>
        <el-button type="text" 
                   style="float: right; margin-right: 10px; color: #409eff;"
                   @click="showWechatDialog">获取微信</el-button>
        <el-button type="text" 
                   style="float: right; margin-right: 10px; color: #409eff;"
                   @click="showReportDialog">举报</el-button>
      </div>
      <div class="user-info">
        <el-avatar :src="requiredHouseDetail.photo" size="large"></el-avatar>
        <div class="user-details">
          <h3>{{ requiredHouseDetail.nikeName }}</h3>
          <p>发布于 {{ requiredHouseDetail.createTime }}</p>
          <p>浏览{{ requiredHouseDetail.viewCount }}次</p>
        </div>
      </div>
      <div class="house-info">
        <h3>90后互联网CP求温馨一居室或loft</h3>
        <p>预算租金：￥{{ requiredHouseDetail.rent }}/月 {{ requiredHouseDetail.tenancyTerm}}{{ requiredHouseDetail.payType}}</p>
        <p>求租户型：{{ requiredHouseDetail.structure}}</p>
        <p>求租类型：{{ requiredHouseDetail.structure}}</p>
        <p>地铁：{{ requiredHouseDetail.location}}</p>
        <p>期望入住时间：{{ requiredHouseDetail.moveTime}}</p>
        <p>求租有效期：{{ requiredHouseDetail.endTime}}</p>
      </div>
      <div class="description">
        <h3>对于房间环境，我希望是这样的</h3>
        <p>{{ requiredHouseDetail.renterRequire }}</p>
      </div>
      <div class="about-me">
        <h3>简单介绍下我的情况，请多指教</h3>
        <p>{{ requiredHouseDetail.landlord }}</p>
      </div>
    </el-card>
    <!--    返回-->
    <el-button type="primary" @click="goBack">返回</el-button>

    <!-- 微信信息弹窗 -->
    <el-dialog
      title="联系方式"
      :visible.sync="wechatDialogVisible"
      width="30%">
      <div class="contact-info">
        <div class="info-item">
          <i class="el-icon-user"></i>
          <span>用户昵称：{{ requiredHouseDetail.nikeName }}</span>
        </div>
        <div class="info-item">
          <i class="el-icon-chat-dot-round"></i>
          <span>微信号：{{ requiredHouseDetail.wechat }}</span>
          <el-button 
            type="text" 
            class="copy-btn"
            v-clipboard:copy="requiredHouseDetail.wechat"
            v-clipboard:success="onCopySuccess"
            v-clipboard:error="onCopyError">
            复制
          </el-button>
        </div>
        <div class="info-item">
          <i class="el-icon-mobile-phone"></i>
          <span>手机号：{{ requiredHouseDetail.phone }}</span>
          <el-button 
            type="text" 
            class="copy-btn"
            v-clipboard:copy="requiredHouseDetail.phone"
            v-clipboard:success="onCopySuccess"
            v-clipboard:error="onCopyError">
            复制
          </el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="wechatDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 电话联系弹窗 -->
    <el-dialog
      title="联系电话"
      :visible.sync="phoneDialogVisible"
      width="30%">
      <div class="contact-info">
        <div class="info-item">
          <i class="el-icon-user"></i>
          <span>用户昵称：{{ requiredHouseDetail.nikeName }}</span>
        </div>
        <div class="info-item">
          <i class="el-icon-mobile-phone"></i>
          <span>手机号：{{ requiredHouseDetail.phone }}</span>
          <el-button 
            type="text" 
            class="copy-btn"
            v-clipboard:copy="requiredHouseDetail.phone"
            v-clipboard:success="onCopySuccess"
            v-clipboard:error="onCopyError">
            复制
          </el-button>
        </div>
        <div class="call-tip">
          <i class="el-icon-warning-outline"></i>
          <span>温馨提示：建议优先通过微信联系，如需电话联系请注意合理时间</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="phoneDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="makePhoneCall">拨打电话</el-button>
      </span>
    </el-dialog>

    <!-- 举报弹窗 -->
    <el-dialog
      title="举报"
      :visible.sync="reportDialogVisible"
      width="30%"
      :before-close="handleClose">
      <div class="report-content">
        <el-form :model="reportForm" ref="reportForm" :rules="reportRules">
          <el-form-item label="举报类型" prop="type">
            <el-select v-model="reportForm.type" placeholder="请选择举报类型">
              <el-option label="虚假信息" value="fake"></el-option>
              <el-option label="违法信息" value="illegal"></el-option>
              <el-option label="骚扰信息" value="harassment"></el-option>
              <el-option label="其他" value="other"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="举报说明" prop="description">
            <el-input
              type="textarea"
              v-model="reportForm.description"
              :rows="4"
              placeholder="请详细描述举报原因（至少10个字）">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reportDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReport" :loading="submitting">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DetailPage',
  data() {
    return {
      requiredHouseDetail: {
      },
      reportDialogVisible: false,
      wechatDialogVisible: false,
      phoneDialogVisible: false,
      submitting: false,
      reportForm: {
        type: '',
        description: ''
      },
      reportRules: {
        type: [
          { required: true, message: '请选择举报类型', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请填写举报说明', trigger: 'blur' },
          { min: 10, message: '描述至少10个字', trigger: 'blur' }
        ]
      },
      isCollected: false,
    };
  },
  methods:{
    goBack(){
      // this.$router.go(-1);
      // 返回上一级
      this.$router.back();
    },
    showReportDialog() {
      this.reportDialogVisible = true;
      
    },
    showWechatDialog() {
      if (!this.requiredHouseDetail.wechat && !this.requiredHouseDetail.phone) {
        this.getContactInfo();
      } else {
        this.wechatDialogVisible = true;
      }
    },
    showPhoneDialog() {
      if (!this.requiredHouseDetail.phone) {
        this.getContactInfo();
      } else {
        this.phoneDialogVisible = true;
      }
    },
    getContactInfo() {
      this.axios.get(`http://localhost:9701/web/required/getContactInfo/${this.requiredHouseDetail.uid}`).then(response => {
        if (response.data.code === 200) {
          this.requiredHouseDetail.wechat = response.data.data.wechat;
          this.requiredHouseDetail.phone = response.data.data.phone;
          this.wechatDialogVisible = true;
        } else {
          this.$message.error('获取联系方式失败');
        }
      }).catch(error => {
        console.error('获取联系方式失败:', error);
        this.$message.error('获取联系方式失败，请稍后重试');
      });
    },
    handleClose(done) {
      if (this.submitting) {
        return;
      }
      this.$confirm('确认关闭？')
        .then(_ => {
          this.resetForm();
          done();
        })
        .catch(_ => {});
    },
    resetForm() {
      this.reportForm.type = '';
      this.reportForm.description = '';
      if (this.$refs.reportForm) {
        this.$refs.reportForm.resetFields();
      }
    },
    submitReport() {
      this.$refs.reportForm.validate(async (valid) => {
        if (!valid) {
          return false;
        }
        
        try {
          this.submitting = true;
          
          // 构建举报数据
          const reportData = {
            rid: this.$route.query.id,  // 被举报的房源ID
            reportType: this.reportForm.type,
            reportContent: this.reportForm.description,
            userId: localStorage.getItem('userId'),  // 从localStorage获取当前登录用户ID
            reportUserId: this.requiredHouseDetail.uid,  // 被举报用户的ID
            uid: this.$route.query.id  // 被举报的房源ID
          };

          // // 判断用户是否登录
          // if (!reportData.userId) {
          //   this.$message.warning('请先登录后再进行举报');
          //   this.reportDialogVisible = false;
          //   // 可以选择跳转到登录页面
          //   // this.$router.push('/login');
          //   return;
          // }

          // 发送举报请求
          const response = await this.axios.post('http://localhost:9701/web/required/reportRequiredHouse', reportData);
          

          if (response.data.code === 200) {
            this.$message.success('举报提交成功');
            this.reportDialogVisible = false;
            this.resetForm();
          } else {
            this.$message.error(response.data.message || '举报提交失败');
          }
        } catch (error) {
          console.error('举报提交失败:', error);
          this.$message.error('举报提交失败，请稍后重试');
        } finally {
          this.submitting = false;
        }
      });
    },
    onCopySuccess() {
      this.$message.success('复制成功');
    },
    onCopyError() {
      this.$message.error('复制失败，请手动复制');
    },
    makePhoneCall() {
      if (this.requiredHouseDetail.phone) {
        window.location.href = `tel:${this.requiredHouseDetail.phone}`;
      } else {
        this.$message.warning('暂无电话号码');
      }
    },
    async handleCollect() {
      try {
        const houseId = this.$route.query.id;
        const userId = this.requiredHouseDetail.uid;

        // 根据当前收藏状态决定是收藏还是取消收藏
        const url = this.isCollected 
          ? `http://localhost:9701/web/required/cancelCollect/${userId}/${houseId}`
          : `http://localhost:9701/web/required/collect/${userId}/${houseId}`;

        const response = await this.axios.get(url);

        if (response.data.code === 200) {
          // 切换收藏状态
          this.isCollected = !this.isCollected;
          // 根据操作显示不同的提示信息
          this.$message.success(this.isCollected ? '收藏成功' : '已取消收藏');
        } else {
          this.$message.error(response.data.message || (this.isCollected ? '取消收藏失败' : '收藏失败'));
        }
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败，请稍后重试');
      }
    },
    async checkCollectionStatus() {
      try {
        const userId = localStorage.getItem('userId');
        const houseId = this.$route.query.id;
        
        if (!userId || !houseId) return;

        const response = await this.axios.get(`http://localhost:9701/web/required/checkCollect/${userId}/${houseId}`);
        if (response.data.code === 200) {
          this.isCollected = response.data.data;
        }
      } catch (error) {
        console.error('获取收藏状态失败:', error);
      }
    }
  },
  created() {
    const  id = this.$route.query.id;
    // 发送axios请求获取详情数据
    if (!id) {
      // 处理错误情况，例如跳转到错误页面或显示默认数据
      return;
    }
    console.log(this.id)
    

    this.axios.get(`http://localhost:9701/web/required/getRequiredHouseById/${id}`).then(response => {
      console.log(response);
      // 处理响应数据


      this.requiredHouseDetail = response.data.data;
      // 其他数据填充
      this.checkCollectionStatus();
    });
  }
};
</script>

<style scoped>
.detail-page {
  max-width: 600px;
  margin: 0 auto;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 20px;
}

.house-info {
  margin-top: 20px;
}

.description {
  margin-top: 20px;
}

.about-me {
  margin-top: 20px;
}

.report-content {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-select {
  width: 100%;
}

.dialog-footer {
  text-align: right;
}

.contact-info {
  padding: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
}

.info-item i {
  margin-right: 10px;
  font-size: 20px;
  color: #409eff;
}

.info-item .copy-btn {
  margin-left: 10px;
  color: #409eff;
}

.info-item span {
  flex: 1;
}

.call-tip {
  margin-top: 20px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.call-tip i {
  color: #e6a23c;
  margin-right: 8px;
  font-size: 16px;
}

.call-tip span {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.el-button.is-collected {
  color: #ff9900 !important;
}

.el-button.is-collected i {
  color: #ff9900;
}

.el-button i {
  margin-right: 4px;
}

.el-button:hover {
  opacity: 0.8;
}
</style>
